using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Rensselaer_Event_Finder
{
    public partial class MainForm : Form
    {

        #region Variables

        public static HomeMDI homeFrm;
        public static AllEventsMDI allEventsFrm;
        public static AllVenuesMDI allVenuesFrm;
        public static RSVPMDI rsvpFrm;
        public static EventMDI eventFrm;
        public static VenueMDI venueFrm;
        public static EventsResultsMDI eventResutsFrm;
        public static SplashScreen splash;
        public static List<Panel> allVenues;
        public static bool manuallyChanged;

        #endregion

        #region Public Methods

        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Displays the MDI form requested in the MainForm container
        /// </summary>
        /// <param name="frm">Form to display (all MDI's live in the MainForm)</param>
        public static void SelectMDIForm(Form frm)
        {
            //shouldn't happen
            if (frm == null)
            {
                MessageBox.Show("Unable to navigate to form.");
                return;
            }

            //show the mdi form requested
            frm.Activate();
            if (frm.WindowState != FormWindowState.Maximized)
            {
                frm.WindowState = FormWindowState.Maximized;
            }
            if (frm.Visible == false)
            {
                frm.Visible = true;
            }
        }

        public void ShowForm()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }


        /// <summary>
        /// Given a location, creates controls to display basic information for the event and adds
        /// the controls to the form
        /// </summary>
        /// <param name="loc">Location to add</param>
        public static Panel Create_Loc_Panel(Location loc)
        {
            //create all controls to add for this location
            System.Windows.Forms.Panel newPanel;
            System.Windows.Forms.LinkLabel newVenueName;
            System.Windows.Forms.PictureBox newPictureBox;
            System.Windows.Forms.Label newVenueCategory;
            System.Windows.Forms.LinkLabel newWebsiteLink;
            System.Windows.Forms.Label newLabel1;
            System.Windows.Forms.Label newLabel2;
            System.Windows.Forms.Label newLabel3;
            RatingControls.StarRatingControl newstarRating;

            newPanel = new System.Windows.Forms.Panel();
            newstarRating = new RatingControls.StarRatingControl();
            newLabel1 = new System.Windows.Forms.Label();
            newLabel2 = new System.Windows.Forms.Label();
            newLabel3 = new System.Windows.Forms.Label();
            newWebsiteLink = new System.Windows.Forms.LinkLabel();
            newVenueCategory = new System.Windows.Forms.Label();
            newVenueName = new System.Windows.Forms.LinkLabel();
            newPictureBox = new System.Windows.Forms.PictureBox(); newPanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(newPictureBox)).BeginInit();

            // 
            // starRating
            // 
            newstarRating.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            newstarRating.BottomMargin = 2;
            newstarRating.Enabled = false;
            newstarRating.HoverColor = System.Drawing.Color.Yellow;
            newstarRating.LeftMargin = 2;
            newstarRating.Location = new System.Drawing.Point(587, 34);
            newstarRating.Name = "starRating";
            newstarRating.OutlineColor = System.Drawing.Color.DarkGray;
            newstarRating.OutlineThickness = 1;
            newstarRating.RightMargin = 2;
            newstarRating.SelectedColor = System.Drawing.Color.RoyalBlue;
            newstarRating.Size = new System.Drawing.Size(120, 18);
            newstarRating.StarCount = 5;
            newstarRating.StarSpacing = 8;
            //Get average rating and apply to star control
            newstarRating.SelectedStar = Globals.getIntAverageRating(loc);
            newstarRating.TabIndex = 7;
            newstarRating.Text = "starRatingControl1";
            newstarRating.TopMargin = 2;
            newstarRating.BackColor = Color.Black;
            newstarRating.ForeColor = Color.White;
            // 
            // Website Label
            // 
            newLabel1.AutoSize = true;
            newLabel1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            newLabel1.Location = new System.Drawing.Point(109, 64);
            newLabel1.Name = loc.Name + "label1";
            newLabel1.Size = new System.Drawing.Size(61, 16);
            newLabel1.TabIndex = 5;
            newLabel1.Text = "Website:";
            newLabel1.BackColor = Color.Black;
            newLabel1.ForeColor = Color.White;
            // 
            // Venue Type Label
            // 
            newLabel2.AutoSize = true;
            newLabel2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            newLabel2.Location = new System.Drawing.Point(109, 34);
            newLabel2.Name = loc.Name + "label2";
            newLabel2.Size = new System.Drawing.Size(79, 16);
            newLabel2.TabIndex = 4;
            newLabel2.Text = "Venue type:";
            newLabel2.BackColor = Color.Black;
            newLabel2.ForeColor = Color.White;
            // 
            // Rating Label
            // 
            newLabel3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            newLabel3.AutoSize = true;
            newLabel3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            newLabel3.Location = new System.Drawing.Point(620, 7);
            newLabel3.Name = loc.Name + "label3";
            newLabel3.Size = new System.Drawing.Size(55, 16);
            newLabel3.TabIndex = 6;
            newLabel3.Text = "Rating";
            newLabel3.BackColor = Color.Black;
            newLabel3.ForeColor = Color.White;
            // 
            // websiteLink
            // 
            newWebsiteLink.AutoSize = true;
            newWebsiteLink.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            newWebsiteLink.Location = new System.Drawing.Point(176, 64);
            newWebsiteLink.Name = loc.Name + "websiteLink";
            newWebsiteLink.Size = new System.Drawing.Size(31, 16);
            newWebsiteLink.TabIndex = 3;
            newWebsiteLink.TabStop = true;

            //Only make it a link if it contains a website
            if (loc.Website != null && loc.Website != "")
            {
                newWebsiteLink.Text = loc.Website;
                newWebsiteLink.Enabled = true;
            }
            else
            {
                newWebsiteLink.Text = "N/A";
                newWebsiteLink.Enabled = false;
            }
            //add handler for website link clicked
            newWebsiteLink.Click += new EventHandler(allVenuesFrm.newWebsiteLink_Click);
            newWebsiteLink.BackColor = Color.Black;
            newWebsiteLink.ForeColor = Color.White;
            newWebsiteLink.LinkColor = Color.White;

            // 
            // venueCategory
            // 
            newVenueCategory.AutoSize = true;
            newVenueCategory.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            newVenueCategory.Location = new System.Drawing.Point(194, 34);
            newVenueCategory.Name = loc.Name + "venueCategory";
            newVenueCategory.Size = new System.Drawing.Size(101, 16);
            newVenueCategory.TabIndex = 2;
            newVenueCategory.BackColor = Color.Black;
            newVenueCategory.ForeColor = Color.White;

            //Build a string containing all categories for this venue
            if (loc.Categories.Count > 0)
            {
                newVenueCategory.Text = loc.Categories[0].Name;
                for (int i = 1; i < loc.Categories.Count; i++)
                {
                    newVenueCategory.Text += ", " + loc.Categories[i].Name;
                }
            }
            else
            {
                newVenueCategory.Text = "N/A";
            }

            // 
            // venueNameLink
            // 
            newVenueName.AutoSize = true;
            newVenueName.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            newVenueName.LinkColor = System.Drawing.Color.Black;
            newVenueName.Location = new System.Drawing.Point(108, 3);
            newVenueName.Name = "venueNameLink";
            newVenueName.Size = new System.Drawing.Size(112, 20);
            newVenueName.TabIndex = 1;
            newVenueName.TabStop = true;
            //add venue name to the text, set the tag as the id, and add the click event handler
            //that loads the venue based on the id stored in the tag
            newVenueName.Text = loc.Name;
            newVenueName.Tag = loc.Id;
            newVenueName.Click += new EventHandler(allVenuesFrm.VenueName_Click);
            newVenueName.BackColor = Color.Black;
            newVenueName.ForeColor = Color.White;
            newVenueName.LinkColor = Color.White;
            // 
            // pictureBox1
            // 
            newPictureBox.Location = new System.Drawing.Point(3, 3);
            newPictureBox.Name = loc.Name + "pictureBox";
            newPictureBox.Size = new System.Drawing.Size(100, 77);
            newPictureBox.TabIndex = 0;
            newPictureBox.TabStop = false;
            newPictureBox.BorderStyle = BorderStyle.Fixed3D;
            newPictureBox.BackColor = Color.Black;
            newPictureBox.ForeColor = Color.White;
            newPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
            newPictureBox.Image = Globals.loadImageFromURL(loc.Image_url);

            // 
            // Venue panel
            // 
            newPanel.Controls.Add(newstarRating);
            newPanel.Controls.Add(newLabel1);
            newPanel.Controls.Add(newLabel2);
            newPanel.Controls.Add(newLabel3);
            newPanel.Controls.Add(newWebsiteLink);
            newPanel.Controls.Add(newVenueCategory);
            newPanel.Controls.Add(newVenueName);
            newPanel.Controls.Add(newPictureBox);
            newPanel.Name = loc.Name + "Panel";
            newPanel.Width = 760;
            newPanel.Height = 83;
            newPanel.TabIndex = 1;
            newPanel.BorderStyle = BorderStyle.Fixed3D;
            newPanel.BackColor = Color.Black;
            newPanel.ForeColor = Color.White;
            newPanel.Tag = loc.Categories;

            return newPanel;

        }
        #endregion

        #region Form Events

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Hide();
            splash = new SplashScreen();
            splash.setStatus("Loading notify icon...");
            splash.Show();

            //Setup notify icon
            //The notify icon control will display it's context menu strip automatically
            //when the right mouse button is clicked
            this.MainNotifyIcon.ContextMenuStrip = this.ContextMenuStrip1;
            this.MainNotifyIcon.Text = this.Text; //tooltip

            splash.setStatus("Syncing with database...");
            Globals.syncDatabase(progressBar);

            splash.setStatus("Setting up forms...");
            //instantiate all MDI forms
            homeFrm = new HomeMDI();
            allEventsFrm = new AllEventsMDI();
            allVenuesFrm = new AllVenuesMDI();
            rsvpFrm = new RSVPMDI();
            venueFrm = new VenueMDI();
            eventFrm = new EventMDI();
            eventResutsFrm = new EventsResultsMDI();

            //set MDI parents to be MainForm
            homeFrm.MdiParent = this;
            allEventsFrm.MdiParent = this;
            allVenuesFrm.MdiParent = this;
            rsvpFrm.MdiParent = this;
            venueFrm.MdiParent = this;
            eventFrm.MdiParent = this;
            eventResutsFrm.MdiParent = this;

            splash.setStatus("Loading home page...");
            //show home form by default
            SelectMDIForm(homeFrm);

            //populate menuTree with base types
            menuTree.SelectedNode = null;
            menuTree.Nodes.Add("Home");
            menuTree.Nodes.Add("Events");
            menuTree.Nodes.Add("Venues");
            menuTree.Nodes.Add("RSVP");

            //add in nodes for categories of events and venues 
            IList<Category> allCategories = Globals.getCategoryService().getAll();
            foreach (Category cat in allCategories)
            {
                TreeNode newEventCat = new TreeNode(cat.Name);
                newEventCat.Tag = cat.Id;
                menuTree.Nodes[1].Nodes.Add(newEventCat);
                TreeNode newVenueCat = new TreeNode(cat.Name);
                newVenueCat.Tag = cat.Id;
                menuTree.Nodes[2].Nodes.Add(newVenueCat);
            }
            //start timer
            clock.Start();
            
            splash.setStatus("Loading event/venue data...");
            allVenues = new List<Panel>();

            IList<Location> dispVenues = new List<Location>();
            dispVenues = Globals.getLocationService().getAll();

            //create each new location
            foreach (Location newloc in dispVenues)
            {
                allVenues.Add(Create_Loc_Panel(newloc));
            }

            splash.setStatus("Loading main form...");

            this.Show();
        }

        private void menuTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
           
        }

         private void menuTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //display form corresponding to node selected
            switch (e.Node.Text)
            {
                case "Home":
                    SelectMDIForm(homeFrm);
                    break;
                case "Events":
                    allEventsFrm.load_events(-1);
                    SelectMDIForm(allEventsFrm);
                    break;
                case "Venues":
                    allVenuesFrm.load_venues(-1);
                    SelectMDIForm(allVenuesFrm);
                    break;
                case "RSVP":
                    rsvpFrm.LoadEvents();
                    SelectMDIForm(rsvpFrm);
                    break;
                default:    //if a child node selected
                    if (e.Node.Parent != null)
                    {
                        //selected event category
                        if (e.Node.Parent.Text == "Events")
                        {
                            //load event page with specified category
                            allEventsFrm.load_events((int)e.Node.Tag);
                            SelectMDIForm(allEventsFrm);
                        }
                        //selected venue category
                        else if (e.Node.Parent.Text == "Venues")
                        {
                            //load venue page with specified category
                            allVenuesFrm.load_venues((int)e.Node.Tag);
                            SelectMDIForm(allVenuesFrm);
                        }
                    }
                    break;

            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // minimize to system tray if form closed by user. Otherwise close normally
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
                MainNotifyIcon.ShowBalloonTip(1000,
                                      this.Text,
                                      "REF is still running...\nRight click tray icon for options.",
                                      ToolTipIcon.Info);
            }
            else
            {
                //close normally
            }
        }

        private void MainNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowForm();
        }

        private void ShowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit(); //don't close the form, we're trapping the UserClosing CloseReason
        }

        private void hideToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void SearchBtn_Click(object sender, EventArgs e)
        {
            if (eventsRadioBtn.Checked)
            {
                IList<Event> searchEvents = Globals.getEventService().getByTextSearch(searchBox.Text);
                if (searchEvents.Count == 0)
                {
                    MessageBox.Show("No results for search: " + searchBox.Text);
                }

                eventResutsFrm.display_events(searchEvents);
                SelectMDIForm(eventResutsFrm);
            }
            else if (venuesRadioBtn.Checked)
            {
                IList<Location> searchVenues = Globals.getLocationService().getByTextSearch(searchBox.Text);
                if (searchVenues.Count == 0)
                {
                    MessageBox.Show("No results for search: " + searchBox.Text);
                }

                allVenuesFrm.display_venues(searchVenues);
                SelectMDIForm(allVenuesFrm);

            }
        }

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoginForm login = new LoginForm();
            if (login.ShowDialog() == DialogResult.OK)
            {
                toolStripStatusLabel1.Text = "User: " + login.usernameBox.Text;
                loginToolStripMenuItem.Visible = false;
                logoutToolStripMenuItem.Visible = true;
            }
            else
            {
                toolStripStatusLabel1.Text = "User: not logged in...";
                loginToolStripMenuItem.Visible = true;
                logoutToolStripMenuItem.Visible = false;
            }
        }

        private void signUpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SignupForm signUp = new SignupForm();
            if (signUp.ShowDialog() == DialogResult.OK)
            {
                toolStripStatusLabel1.Text = "User: " + signUp.usernameBox.Text;
                loginToolStripMenuItem.Visible = false;
                signUpToolStripMenuItem.Visible = false;
                logoutToolStripMenuItem.Visible = true;
            }
            else
            {
                toolStripStatusLabel1.Text = "User: not logged in...";
                loginToolStripMenuItem.Visible = true;
                signUpToolStripMenuItem.Visible = true;
                logoutToolStripMenuItem.Visible = false;
            }
        }

        private void clock_Tick(object sender, EventArgs e)
        {
            progressBar.Visible = true;
            syncLabel.Visible = true;
            Globals.syncDatabase(progressBar);
            progressBar.Visible = false;
            syncLabel.Visible = false;
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "User: not logged in...";
            loginToolStripMenuItem.Visible = true;
            signUpToolStripMenuItem.Visible = true;
            logoutToolStripMenuItem.Visible = false;
            Globals.CurrentUser = null;

            rsvpFrm.clearEvents();
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            splash.Close();
        }

  #endregion

       

        
         
    }


}